package main

import (
	"cybertwin/pb/model"
	"cybertwin/utils/protocol"

	"fmt"
	"net"
	"os"
	"time"

	"github.com/rs/zerolog" //日志框架
	log "github.com/sirupsen/logrus"
	"google.golang.org/protobuf/proto"
)

// var m = flag.Int("n", 100, "-n 100: 输入的创建数量")

func init() {
	zerolog.TimeFieldFormat = time.DateTime
}

func registerUser(username string) (uid string, ctid string) {
	// 注册协议封装

	registerParam := &model.UserRegisterParam{
		Username: username,
	}

	codec := protocol.AccessProtocolCodec{}
	marshal, err := proto.Marshal(registerParam) // 序列化请求参数
	if err != nil {
		log.Errorln("[RegisterUser]-序列化registerParam失败:", err.Error())
		return
	}
	encode, err := codec.EncryptEncode(marshal, protocol.TYPE_USER_REGISTER) // 生成协议
	if err != nil {
		log.Errorln("[RegisterUser]-EncryptEncode registerParam失败:", err.Error())
		return
	}
	dial, err := net.Dial("tcp", "127.0.0.1:8080")
	defer dial.Close()
	size, err := dial.Write(encode)
	if err != nil {
		log.Errorln("[RegisterUser]-向注册中心write数据失败:", err.Error())
		return
	}
	log.Infof("[RegisterUser-发送注册请求，%dbytes数据", size)

	var buf = make([]byte, 1024)
	size, err = dial.Read(buf)
	buf = buf[:size]
	if err != nil {
		log.Errorln("[RegisterUser]-读取注册消息失败", err.Error())
		return
	}
	data, typeName, _, err := codec.DecodeFromBytes(buf)
	if typeName != protocol.TYPE_USER_RESPONSE.GetName() {
		log.Errorln("[RegisterUser]-类型错误，expected:TYPE_USER_RESPONSE, actual:%s", typeName)
		return
	}
	resp := &model.UserRegisterResp{}
	err = proto.Unmarshal(data, resp)
	if err != nil {
		log.Errorln("[RegisterUser]-反序列化RegisterResp失败")
		return
	}
	return
}

func main() {
	// flag.Parse()
	// log.Infof("[RegisterUser-main]-解析到命令行参数为%d", m)
	fileName := "user_info.txt"
	file, err := os.OpenFile(fileName, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
	if err != nil {
		// 	log.Errorf("[RegisterUser-main]-打开文件/创建文件失败: %s", err.Error())
		// 	return
	}

	username := "user_02"
	uid, ctid := registerUser(username)
	file.Write([]byte(fmt.Sprintf("%s %s\n", uid, ctid)))
}
